﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace MT4Trainer
{
    using System.Collections;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Security;
    using System.Security.Permissions;
    using System.Threading;

    using Encog;
    using Encog.App.Analyst;
    using Encog.App.Analyst.CSV.Normalize;
    using Encog.App.Analyst.Missing;
    using Encog.App.Analyst.Report;
    using Encog.App.Analyst.Script.Normalize;
    using Encog.App.Analyst.Util;
    using Encog.App.Analyst.Wizard;
    using Encog.ML;
    using Encog.ML.Data;
    using Encog.ML.Data.Buffer;
    using Encog.ML.Data.Buffer.CODEC;
    using Encog.ML.Train;
    using Encog.Util.CSV;
    using Encog.Util.File;
    using Encog.Util.Logging;

    using NLog.Config;
    using NLog.Targets;

    public partial class AnalystHelperForm : Form, IAnalystListener
    {
        public AnalystHelperForm()
        {
            InitializeComponent();

        }

        private AnalystWizard analystWizard { get; set; }
        private EncogAnalyst Analyst { get; set; }
        private Stopwatch _sw = new Stopwatch();
        private string Headers { get; set; }
        private NLog.Logger mLogger;
        public string SafeFileName
        {
            get
            {
                new FileIOPermission(PermissionState.Unrestricted).Assert();
                string fullPath = ChosenSourceFile;
                CodeAccessPermission.RevertAssert();
                if (string.IsNullOrEmpty(fullPath))
                {
                    return "";
                }

                string safePath = RemoveSensitivePathInformation(fullPath);
                return safePath;
            }
        }
        private BindingList<string> HeaderList = new BindingList<string>();

        public string egaFile { get; set; }
        private bool ShouldStopRunningCommand;

        private bool stopAllAnalyst;

        private bool ShouldCancelRunningCommand;

        private static string RemoveSensitivePathInformation(string fullPath)
        {
            return System.IO.Path.GetFileName(fullPath);
        }

        /// <summary>
        ///  Gets or sets the chosen source file.
        ///  This is the CSV file , that will be normalized or that the Analyst will work on.
        /// </summary>
        /// <value>
        ///  The chosen source file.
        /// </value>
        private string ChosenSourceFile { get; set; }

        /// <summary>
        ///  Event handler. Called by TextBoxFileSource for double click events.
        /// </summary>
        /// <param name="sender"> Source of the event. </param>
        /// <param name="e"> Drag event information. </param>
        private void TextBoxFileSource_DoubleClick(object sender, EventArgs e)
        {
            mLogger.Trace(() => "Double clicked on TextBox source , open file dialog.");
            using (var open = new OpenFileDialog())
            {
                open.Filter = "CSV files (.csv) | *.csv|Text Files (.txt)|*.txt";
                if (open.ShowDialog() == DialogResult.OK)
                {
                    mLogger.Trace(() => "Dialog Result ok found..");
                    
                    dataGridView1.ResetText();
                    //   dataGridView1 = new DataGrid();
                    ChosenSourceFile = open.FileName;
                    this.ParseFirst4LinesOfFile();
                    this.StartAnalystButton.Enabled = true;
                    this.TextBoxFileSource.Text = SafeFileName;
                    return;
                }
            }
        }

        /// <summary>
        ///  Event handler. Called by TextBoxFileSource for drag enter events.
        /// </summary>
        /// <param name="sender"> Source of the event. </param>
        /// <param name="e"> Drag event information. </param>
        private void TextBoxFileSource_DragEnter(object sender, DragEventArgs e)
        {
            mLogger.Trace(() => "A file was dragged in the source text box..");

            try
            {
                Array a = (Array)e.Data.GetData(DataFormats.FileDrop);

                if (a != null)
                {
                    // Extract string from first array element
                    // (ignore all files except first if number of files are dropped).
                    string s = a.GetValue(0).ToString();
                    dataGridView1.ResetText();
                    //     dataGridView1 = new DataGrid();
                    this.ChosenSourceFile = s;
                    this.ParseFirst4LinesOfFile();
                    this.StartAnalystButton.Enabled = true;
                    this.TextBoxFileSource.Text = SafeFileName;
                    // // Call OpenFile asynchronously.
                    // // Explorer instance from which file is dropped is not responding
                    // // all the time when DragDrop handler is active, so we need to return
                    // // immidiately (especially if OpenFile shows MessageBox).

                    //// this.BeginInvoke(m_DelegateOpenFile, new Object[] { s });

                    // this.Activate();        // in the case Explorer overlaps this form
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Error in DragDrop function: " + ex.Message);
                mLogger.Error("Error in Drag Drop :" + ex);
                // don't show MessageBox here - Explorer is waiting !
            }
        }

        private void AnalystHelperForm_Load(object sender, EventArgs e)
        {
            this.FillAllComboxAndInits();
            //mLogger = NLog.LogManager.GetCurrentClassLogger();
            AddNewNLogTarget();
            mLogger.Info("Analyst Form started.");
        }

        /// <summary>
        ///  When the form inits , we need to fill the combo boxes , and various text boxes with default values.
        /// </summary>
        private void FillAllComboxAndInits()
        {
            //Lets fill the format Analyst file format combobox.
            object[] names = Enum.GetNames(typeof(AnalystFileFormat));
            this.FileFormatComboxBox.Items.AddRange(names);
            this.FileFormatComboxBox.SelectedIndex = 0;
            //Lets fill the format Analyst file format combobox.
            object[] MachineLearnings = Enum.GetNames(typeof(WizardMethodType));
            this.NetworkComboBox.Items.AddRange(MachineLearnings);
            this.NetworkComboBox.SelectedIndex = 0;
            //Lets grab all possible analyst goals.
            object[] AnalyGoals = Enum.GetNames(typeof(AnalystGoal));
            this.AnalystGoalComboBox.Items.AddRange(AnalyGoals);
            this.AnalystGoalComboBox.SelectedIndex = 0;
            //Lets grab all possible normalization ranges.
            object[] NormalizationRanges = Enum.GetNames(typeof(NormalizeRange));
            this.NormalizeRangeCombo.Items.AddRange(NormalizationRanges);
            this.NormalizeRangeCombo.SelectedIndex = 0;

            List<String> missingList = new List<String>();
            missingList.Add("DiscardMissing");
            missingList.Add("MeanAndModeMissing");
            missingList.Add("NegateMissing");
            foreach (string s in missingList)
            {
                this.MissingValuesCombox.Items.Add(s);
                
            }

            this.MissingValuesCombox.SelectedIndex = 0;

            this.TaskWorkCheckBox.SetItemCheckState(0, CheckState.Checked);
            this.TaskWorkCheckBox.SetItemCheckState(3, CheckState.Checked);
            this.TaskWorkCheckBox.SetItemCheckState(4, CheckState.Checked);



        }






        private void ParseFirst4LinesOfFile()
        {

            if (!string.IsNullOrEmpty(ChosenSourceFile) && File.Exists(ChosenSourceFile))
            {
                using (TextReader re = new StreamReader(ChosenSourceFile))
                { 
                    var header = re.ReadLine();
                    var line2 = re.ReadLine();
                     if (!string.IsNullOrEmpty(header) && !string.IsNullOrEmpty(line2))
                    {
                    this.richTextBox1.AppendText(header);
                    this.richTextBox1.AppendText("\n");
                    this.richTextBox1.AppendText(line2);

                   

                        this.Headers = header;
                        var queried = from p in Headers.Split(',') select p;
                        //  dataGridView1.DataSource = queried.ToArray();

                        
                        HeaderList.Clear();
                        foreach (var s in queried) HeaderList.Add(s);

                        //dataGridView1.DataSource = HeaderList;


                        dataGridView1.ColumnHeadersVisible = true;
                        dataGridView1.DataSource = null;
                        dataGridView1.DataSource = HeaderList;

                        TargetFieldComboBox.Items.Clear();
                        foreach (var s in HeaderList) TargetFieldComboBox.Items.Add(s);

                       // this.TargetFieldComboBox.Items.AddRange(HeaderList.ToArray());




                    }
                     else
                         RichLogAnalyst.AppendText("Couldn't parse headers or next line...");

                }
            }
        }

        #region change the format for the data grid.
        private void commaToolStripMenuItem_Click(object sender, EventArgs e)
        {

            var queried = from p in Headers.Split(',') select p;

            HeaderList.Clear();
            foreach (var s in queried) HeaderList.Add(s);
            dataGridView1.ColumnHeadersVisible = true;
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = HeaderList;
            TargetFieldComboBox.Items.Clear();
            this.TargetFieldComboBox.Items.AddRange(HeaderList.ToArray());
        }

        private void dotToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HeaderList.Clear();
            var queried = from p in Headers.Split('.') select p;
            HeaderList.Clear();
            foreach (var s in queried) HeaderList.Add(s);
            dataGridView1.ColumnHeadersVisible = true;
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = HeaderList;
            TargetFieldComboBox.Items.Clear();
            this.TargetFieldComboBox.Items.AddRange(HeaderList.ToArray());

        }

        private void ToolStripSeparatorTextbox_TextChanged(object sender, EventArgs e)
        {
            HeaderList.Clear();
            string text = ToolStripSeparatorTextbox.Text;
            char pchar = Convert.ToChar(text);
            var queried = from p in Headers.Split(pchar) select p;
            HeaderList.Clear();
            foreach (var s in queried) HeaderList.Add(s);
            dataGridView1.ColumnHeadersVisible = true;
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = HeaderList;
            TargetFieldComboBox.Items.Clear();
            this.TargetFieldComboBox.Items.AddRange(HeaderList.ToArray());
        }


        private void spaceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HeaderList.Clear();
            var queried = from p in Headers.Split(' ') select p;
            HeaderList.Clear();
            foreach (var s in queried) HeaderList.Add(s);
            dataGridView1.ColumnHeadersVisible = true;
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = HeaderList;
            TargetFieldComboBox.Items.Clear();
            this.TargetFieldComboBox.Items.AddRange(HeaderList.ToArray());
        }

        private void OnCommaFormatSelected(object sender, EventArgs e)
        {
            //var queried = from p in Headers.Split(';') select p;
            //HeaderList.Clear();
            //foreach (var s in queried) HeaderList.Add(s);
            //dataGridView1.ColumnHeadersVisible = true;
            //dataGridView1.DataSource = null;
            //dataGridView1.DataSource = HeaderList;
            //TargetFieldComboBox.Items.Clear();
            //this.TargetFieldComboBox.Items.AddRange(HeaderList.ToArray());


            
            var queried = from p in Headers.Split(';') select p;
            //  dataGridView1.DataSource = queried.ToArray();
            

            HeaderList.Clear();
            foreach (var s in queried) HeaderList.Add(s);

            //dataGridView1.DataSource = HeaderList;


            dataGridView1.ColumnHeadersVisible = true;
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = HeaderList;

            TargetFieldComboBox.Items.Clear();
            foreach (var s in HeaderList) TargetFieldComboBox.Items.Add(s);
        }

        private void sToolStripMenuItem_TextChanged(object sender, EventArgs e)
        {

        }

        BindingList<string> CreateDataSource(List<string> headeritems)
        {

           BindingList<string> Headers = new BindingList<string>(headeritems);

            //DataView dv;
            //using (DataTable dt = new DataTable())
            //{
            //    DataRow dr;
            //    foreach (string headeritem in headeritems)
            //    {
            //        dt.Columns.Add(new DataColumn(headeritem, typeof(string)));
            //    }
               

            //    dv = new DataView(dt);
            //}
            //return dv;

            return Headers;
        }
        #endregion
        public void AddNewNLogTarget()
        {

            var richtgt = new RichTextBoxTarget
                {
                    AutoScroll = true,
                    ControlName = "RichLogAnalyst",
                    FormName = "AnalystHelperForm",
                    UseDefaultRowColoringRules = true,
                    Name = "RichAnalyst",
                    ToolWindow = false
                };

            NLog.LogManager.Configuration.AddTarget("RichAnalyst", richtgt);
            NLog.LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Trace, richtgt));

            NLog.LogManager.ReconfigExistingLoggers();

            mLogger = NLog.LogManager.GetCurrentClassLogger();


        }

        public double CalculateError(IMLMethod meth, IMLDataSet train)
        {
            IMLMethod method = meth;
            IMLDataSet data = train;
            return ((IMLError)method).CalculateError(data);
        }


        public void Report(string filename, EncogAnalyst analy)
        {

            FileInfo info = new FileInfo(filename);
            var report = new AnalystReport(analy);
            report.ProduceReport(info);
        }




        private void StartAnalystButton_Click(object sender, EventArgs e)
        {


            try
            {
                mLogger.Trace(() => "starting the analyst with chosen file :" + ChosenSourceFile);
                String targetCSVFile = ChosenSourceFile;
                egaFile = FileUtil.ForceExtension(targetCSVFile, "ega");
                Analyst = new EncogAnalyst();




                NLogEncogLogger encLogger = new NLogEncogLogger(mLogger);


                Encog.EncogFramework.Instance.RegisterPlugin(encLogger);


                // Analyst.AddAnalystListener(new NLogAnalystBridge());
                Analyst.AddAnalystListener(this);


                Encog.EncogFramework.Instance.LoggingPlugin.Log(EncogLogging.LogLevel.Critical, "##########Test Message");


                AnalystStarted = true;
                ShouldStopRunningCommand = false;
                analystWizard = new AnalystWizard(Analyst);
                bool headers = !HasHeadersRadio.Checked;
                this.RunAllTaskButton.Enabled = true;
                this.CancelCurrentAnalystCommandButton.Enabled = true;
                this.StopAllButton.Enabled = true;
                var enfileformat = AnalystFileFormat.DecpntComma;
                //Lets try to parse the chosen analyst file format.
                Enum.TryParse(FileFormatComboxBox.Text, true, out enfileformat);
                mLogger.Trace("Chosen file format  :" + enfileformat);
                //If we can't parse the goal , we ll just use regression.
                AnalystGoal goal = (AnalystGoal)(Enum.Parse(typeof(AnalystGoal), this.AnalystGoalComboBox.Text) ?? AnalystGoal.Regression);
                mLogger.Trace("Analyst goal chosen :" + goal);
                //Lets set the target field..
                analystWizard.TargetFieldName = string.IsNullOrEmpty(TargetFieldComboBox.Text) ? string.Empty : TargetFieldComboBox.Text;
                mLogger.Trace("Target Field  :" + analystWizard.TargetFieldName);
                WizardMethodType methodType = (WizardMethodType)(Enum.Parse(typeof(WizardMethodType), this.NetworkComboBox.Text) ?? WizardMethodType.FeedForward);
                analystWizard.MethodType = methodType;
                mLogger.Trace("Analyst method type :" + methodType);
                NormalizeRange wizNormRange = (NormalizeRange)(Enum.Parse(typeof(NormalizeRange), this.NormalizeRangeCombo.Text) ?? NormalizeRange.NegOne2One);
                mLogger.Trace("Getting wizard range :" + wizNormRange);
                analystWizard.Range = wizNormRange;
                analystWizard.Goal = goal;
                analystWizard.Missing = TranslateMissing(MissingValuesCombox.Text);



                int leadct = 0;
                int.TryParse(LeadCountTextBox.Text, out leadct);

                int lagct = 0;
                int.TryParse(LagCountTextBox.Text, out lagct);
                int maxites = 0;
                int.TryParse(MaxIterationBox.Text, out maxites);
                if (maxites > 0) this.Analyst.MaxIteration = maxites;
                //Get max error to train too..
                analystWizard.MaxError = MaxErrorTrackBar.Value;


                mLogger.Trace("Got Lead count : " + leadct + " Lag count : " + lagct);
                analystWizard.LagWindowSize = lagct;
                analystWizard.LeadWindowSize = leadct;
                analystWizard.IncludeTargetField = IncludeTargetRadioBox.Checked;

                ////timeseries if lead or lag count > 0.
                //Analyst.TimeSeries = (lagct > 0 || leadct > 0) ? true : false;

                mLogger.Trace("Including target field : " + IncludeTargetRadioBox.Checked);
                analystWizard.TaskNormalize = TaskWorkCheckBox.GetItemCheckState(0) == CheckState.Checked ? true : false;
                analystWizard.TaskRandomize = TaskWorkCheckBox.GetItemCheckState(1) == CheckState.Checked ? true : false;
                analystWizard.TaskSegregate = TaskWorkCheckBox.GetItemCheckState(2) == CheckState.Checked ? true : false;
                analystWizard.TaskBalance = TaskWorkCheckBox.GetItemCheckState(3) == CheckState.Checked ? true : false;
                analystWizard.TaskCluster = TaskWorkCheckBox.GetItemCheckState(4) == CheckState.Checked ? true : false;
                mLogger.Info(string.Format("Doing Tasks Normalize :{0} Randomize:{1} Segregate :{2} Balance :{3} Cluster:{4}", this.analystWizard.TaskNormalize, this.analystWizard.TaskRandomize, this.analystWizard.TaskSegregate, this.analystWizard.TaskBalance, this.analystWizard.TaskCluster));
                _sw.Start();
                mLogger.Info(@"Analyzing data....");
                // var t = Task.Factory.StartNew(() => analystWizard.Wizard(new FileInfo(targetCSVFile), headers, enfileformat));

                analystWizard.Wizard(new FileInfo(targetCSVFile), headers, enfileformat);




                mLogger.Info(@"Saving analyst file");
                Analyst.Save(egaFile);
                mLogger.Info("Elapsed time for this csv analysis :" + _sw.Elapsed);
                _sw.Stop();
                EditScriptButton.Enabled = true;
            }
            catch (Exception ex)
            {
                
                mLogger.Error(ex);
            }
          
        }

        private void ConvertCSV2EGB(string sourcefile, string targetfile, int inputCount, int outputCount, bool useheaders = true)
        {

            if (inputCount == 0)
            {
                Console.WriteLine(@"Must specify an input count.");
                return;
            }

            AnalystFileFormat format1 = ConvertStringConst.String2AnalystFileFormat(CSVFormat.English.ToString());
            CSVFormat format = ConvertStringConst.ConvertToCSVFormat(format1);

            new FileInfo(targetfile).Delete();
            IDataSetCODEC codec = new CSVDataCODEC(sourcefile, format, useheaders,
                                                   inputCount, outputCount, false);
            var loader = new BinaryDataLoader(codec) { Status = new ConsoleStatusReportable() };
            _sw.Start();
            loader.External2Binary(targetfile);
        }
        protected bool AnalystStarted { get; set; }

        private static IHandleMissingValues TranslateMissing(String m)
        {
            if (m.Equals("DiscardMissing"))
            {
                return new DiscardMissing();
            }
            if (m.Equals("MeanAndModeMissing"))
            {
                return new MeanAndModeMissing();
            }
            if (m.Equals("NegateMissing"))
            {
                return new NegateMissing();
            }
            return new DiscardMissing();
        }
        private void ShowError(string message)
        {
            MessageBox.Show(message);
        }

        private void MaxErrorTrackBar_Scroll(object sender, EventArgs e)
        {
            this.ErrorTextBox.Text = MaxErrorTrackBar.Value.ToString(CultureInfo.InvariantCulture);
        }

        #region Implementation of IAnalystListener

        /// <summary>
        /// Request stop the entire process.
        /// </summary>
        ///
        public void RequestShutdown()
        {
            mLogger.Info("Analyst Requesting Shutdown..");
            mLogger.Info("Clearing all task left.");
            Analyst.StopCurrentTask();
            Analyst.Script.ClearTasks();
        }

        /// <summary>
        /// Request to cancel current command.
        /// </summary>
        ///
        public void RequestCancelCommand()
        {
            mLogger.Info("Analyst Cancelling command");
        }

        /// <returns>True if the entire process should be stopped.</returns>
        public bool ShouldShutDown()
        {
            mLogger.Warn("Analyst Should shut down.");
            return stopAllAnalyst;

        }

        /// <returns>True if the current command should be stopped.</returns>
        public bool ShouldStopCommand()
        {
            mLogger.Info("Analyst Requesting command stop.");
            return ShouldStopRunningCommand;
        }

        /// <summary>
        /// Report that a command has begun.
        /// </summary>
        /// <param name="total">The total parts.</param>
        /// <param name="current">The current part.</param>
        /// <param name="name">The name of that command.</param>
        public void ReportCommandBegin(int total, int current, string name)
        {
            mLogger.Info("Beginning Analyst work task :{0} Count : {1} / {2}", name, current, total);
        }

        /// <summary>
        /// Report that a command has ended.
        /// </summary>
        /// <param name="canceled">True if this command was canceled.</param>
        public void ReportCommandEnd(bool canceled)
        {
            if (canceled)
            {
                mLogger.Warn("Command was cancelled ...");
                return;
            }
            mLogger.Warn("Command finished .");

        }

        /// <summary>
        /// Report that training has begun.
        /// </summary>
        ///
        public void ReportTrainingBegin()
        {
            mLogger.Info("Training is starting ....");
        }

        /// <summary>
        /// Report that training has ended.
        /// </summary>
        ///
        public void ReportTrainingEnd()
        {
            mLogger.Info("Training has finished ...");
        }

        /// <summary>
        /// Report progress on training.
        /// </summary>
        ///
        /// <param name="train">The training object.</param>
        public void ReportTraining(IMLTrain train)
        {
            mLogger.Debug("Training Progression :" + train.IterationNumber + " Current Error :" + train.Error);
        }

        /// <summary>
        /// Report progress on a task.
        /// </summary>
        ///
        /// <param name="total">The total number of commands.</param>
        /// <param name="current">The current command.</param>
        /// <param name="message">The message.</param>
        public void Report(int total, int current, string message)
        {
            mLogger.Warn("Task Progression :{0} Count : {1} / {2}", message, current, total);
        }

        #endregion

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void StopCommandButton_Click(object sender, EventArgs e)
        {
            this.ShouldStopRunningCommand = true;
            this.ShouldStopCommand();
        }

        private void StopAllButton_Click(object sender, EventArgs e)
        {
            stopAllAnalyst = true;
            this.RequestShutdown();

        }

        private void CancelCurrentAnalystCommandButton_Click(object sender, EventArgs e)
        {
            ShouldCancelRunningCommand = true;
        }

        private void RunAllTaskButton_Click(object sender, EventArgs e) { 
            
            Task.Run(() => this.DoAllAnalystTasks());
        }

        private void DoAllAnalystTasks()
        {
            var analyst = new EncogAnalyst();
            analyst.AddAnalystListener(this);
            // var t = Task.Factory.StartNew(() => analyst.AddAnalystListener(this));


            analyst.Load(new FileInfo(this.egaFile));
            analyst.ExecuteTask("task-full");
        }

        private void EditScriptButton_Click(object sender, EventArgs e)
        {
            using (ScriptEditor editor = new ScriptEditor(egaFile))
            {
                editor.ShowDialog();
            }
        }

        private void OpenScriptEditorButton_Click(object sender, EventArgs e)
        {
            using (ScriptEditor edit = new ScriptEditor())
            {
                edit.ShowDialog();
            }
        }

        private void FragDatesButton_Click(object sender, EventArgs e)
        {

        }



        #region date parsings.
        private int GetDaysFromDate(string date)
        {
            if (UseDatesCheckBox.Checked)
            {
                DateTime p = new DateTime();
                string dateformat = DateTimeFormatTextBox.Text;
                var dtParsed = DateTime.TryParseExact(date, dateformat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out p);
                if (dtParsed) return p.Day;
            }
            return 0;
        }

        private int GetYearFromDate(string date)
        {
            if (UseDatesCheckBox.Checked)
            {
                DateTime p = new DateTime();
                string dateformat = DateTimeFormatTextBox.Text;
                var dtParsed = DateTime.TryParseExact(date, dateformat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out p);
                if (dtParsed) return p.Year;
            }
            return 0;
        }

        private int GetMonthFromDate(string date)
        {
            if (UseDatesCheckBox.Checked)
            {
                DateTime p = new DateTime();
                string dateformat = DateTimeFormatTextBox.Text;
                var dtParsed = DateTime.TryParseExact(date, dateformat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out p);
                if (dtParsed) return p.Month;
            }
            return 0;
        }

        private int GetDayOfWeekFromDate(string date)
        {
            if (UseDatesCheckBox.Checked)
            {
                DateTime p = new DateTime();
                string dateformat = DateTimeFormatTextBox.Text;
                var dtParsed = DateTime.TryParseExact(date, dateformat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out p);
                if (dtParsed) return (int)p.DayOfWeek;
            }
            return 0;
        }

        private int GetHoursFromDate(string time)
        {
            if (UseDatesCheckBox.Checked)
            {
                //Time will be in format HH:mm:ss.fff ...Or just HH:mm:ss.... or even HH:mm...
                int p = 0;
                //We split the string by : separator...
                var xx = time.Split(':');
                //we take the first item in our split.
                int.TryParse(xx[0], NumberStyles.Number, CultureInfo.InvariantCulture, out p);
                return p;
            }
            return 0;
        }

        private int GetMinutesFromDate(string time)
        {
            if (UseDatesCheckBox.Checked)
            {
                //Time will be in format HH:mm:ss.fff ...Or just HH:mm:ss.... or even HH:mm...
                int p = 0;
                //We split the string by : separator...
                var xx = time.Split(':');
                //we take the first item in our split.
                int.TryParse(xx[1], NumberStyles.Number, CultureInfo.InvariantCulture, out p);
                return p;
            }
            return 0;
        }

        private int GetSecondsFromDate(string time)
        {
            if (UseDatesCheckBox.Checked)
            {
                //Time will be in format HH:mm:ss.fff ...Or just HH:mm:ss.... or even HH:mm...
                int p = 0;
                //We split the string by : separator...
                var xx = time.Split(':');
                //we take the first item in our split.
                int.TryParse(xx[2], NumberStyles.Number, CultureInfo.InvariantCulture, out p);
                return p;
            }
            return 0;
        }
        private int GetMilliSecondsFromDate(string time)
        {
            if (UseDatesCheckBox.Checked)
            {
                //Time will be in format HH:mm:ss.fff ...Or just HH:mm:ss.... or even HH:mm...
                int p = 0;
                //the string contains . , which means it has milliseconds...
                if (time.Contains("."))
                {
                    //We split the string by : separator...
                    int wherre = time.First(x => x == '.');

                    //Lets parse the milliseconds , starting from the found  dot.
                    int.TryParse(time.Substring(wherre + 1, time.Length), NumberStyles.Number, CultureInfo.InvariantCulture, out p);
                    return p;
                }
            }
            return 0;
        }
        #endregion
        #region change the use dates group visibility
        private void UseDatesCheckBox_CheckStateChanged(object sender, EventArgs e)
        {
            if (UseDatesCheckBox.Checked)
            {
                this.TimeFormatLabel.Visible = true;
                this.TimeFormatTextBox.Visible = true;
                this.DateFormatLabel.Visible = true;
                this.DateTimeFormatTextBox.Visible = true;

            }
            else
            {
                this.TimeFormatLabel.Visible = false;
                this.TimeFormatTextBox.Visible = false;
                this.DateFormatLabel.Visible = false;
                this.DateTimeFormatTextBox.Visible = false;
            }
        }
        #endregion

        private void LoadScriptButton_Click(object sender, EventArgs e)
        {
            mLogger.Trace(() => "Double clicked on Open script button, open file dialog.");
            using (var open = new OpenFileDialog())
            {
                open.Filter = "ega files (.ega) | *.ega";
                if (open.ShowDialog() == DialogResult.OK)
                {
                    mLogger.Trace(() => "Dialog Result ok found..");
                    dataGridView1.ResetText();
                    this.StartAnalystButton.Enabled = false;
                    Analyst.Load(open.FileName);
                    mLogger.Info("Loaded analyst script to memory...");
                    return;
                }
            }
        }

        private void AnalystHelperForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Lets remove the logger.
            NLog.LogManager.Configuration.RemoveTarget("RichAnalyst");
        }

        private void FileFormatComboxBox_SelectedIndexChanged(object sender, EventArgs e)
        {

           
            if (FileFormatComboxBox.SelectedItem is AnalystFileFormat)
            {
                AnalystFileFormat format = (AnalystFileFormat) Enum.Parse(typeof (AnalystFileFormat), this.FileFormatComboxBox.SelectedItem.ToString());



            }
        }

        private void HelpButton_Click(object sender, EventArgs e)
        {
            using (var frm = new HelpForm())
            {
                frm.ShowDialog();
            }
        }



    }
}
